package com.dempsey.common.security.interceptor;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.fastjson.JSON;
import com.dempsey.api.model.LoginUser;
import com.dempsey.common.core.utils.ServletUtils;
import com.dempsey.common.security.constant.SecurityConstants;
import com.dempsey.common.security.context.SecurityContextHolder;
import com.dempsey.common.security.utils.SecurityUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;

/**
 * 自定义请求头拦截器，将Header数据封装到线程变量中方便获取
 *
 * @author Dempsey
 */
public class HeaderInterceptor implements AsyncHandlerInterceptor {

    private static final Log log = LogFactory.get();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        String loginUserJsonString = ServletUtils.getHeader(request, SecurityConstants.LOGIN_USER);
        String loginUserJsonStringDecodeUTF8 = URLDecoder.decode(loginUserJsonString, "utf-8");
        LoginUser loginUser = JSON.parseObject(loginUserJsonStringDecodeUTF8, LoginUser.class);

        SecurityUtils.setLoginUser(loginUser);
        String requestURI = request.getRequestURI();
        log.info("拦截请求{}，将{}加入线程上下文", requestURI, loginUser);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        SecurityContextHolder.remove();
    }
}
